<template>
  <a-layout>
    <a-affix :offset-top="top">
      <a-layout-header :style="headerStyle">
        <a-row>
          <a-col :span="5">
            <div style="display: flex">
              <router-link to="/">
                <a-image
                  :width="180"
                  :preview="false"
                  :src="headerLogo"
                />
              </router-link>
              <div style="display: flex; align-items: end; margin-left: 10px">
                <h3 style="font-weight: bold; color: #606266">我的商城</h3>
              </div>
            </div>
          </a-col>
          <a-col
            :span="15"
            style="justify-content: center; align-items: center; display: flex"
          >
            <div style="color: rgb(165, 162, 162)">
              <a-space :size="30">
                <router-link to="/" style="text-decoration: underline"
                  ><HomeOutlined
                    style="color: #529b2e; margin-right: 5px"
                  />返回首页>
                </router-link>
                <a-dropdown>
                  <router-link to=""
                    >账号设置
                    <DownOutlined style="color: #73767a; fontsize: 12px" />
                  </router-link>
                  <template #overlay>
                    <a-menu>
                      <a-menu-item>
                        <a
                          @click="setVisible"
                          href="javascript:;"
                          style="font-size: 10px"
                          ><UserOutlined
                            style="color: #409eff; margin-right: 3px"
                          />个人信息</a
                        >
                      </a-menu-item>
                      <a-menu-item>
                        <a
                          @click="setModelVisible"
                          href="javascript:;"
                          style="font-size: 10px"
                          ><LockOutlined
                            style="color: #409eff; margin-right: 3px"
                          />修改密码</a
                        >
                      </a-menu-item>
                    </a-menu>
                  </template>
                </a-dropdown>
                <a-tooltip color="green" placement="topRight">
                  <template #title>
                    <span
                      v-text="isConfrim === true ? confirm : notConfirm"
                    ></span>
                  </template>
                  <router-link to="" @click="certificationRight"
                    ><ContactsOutlined
                      style="color: #409eff; margin-right: 5px"
                    />实名认证
                  </router-link>
                </a-tooltip>

                <a-dropdown>
                  <router-link to=""
                    >收藏夹
                    <DownOutlined style="color: #73767a; fontsize: 12px" />
                  </router-link>
                  <template #overlay>
                    <a-menu>
                      <a-menu-item>
                        <router-link style="font-size: 10px" to="/collectgoods">
                          <StarOutlined
                            style="color: red; margin-right: 3px"
                          />收藏的宝贝
                        </router-link>
                      </a-menu-item>
                      <a-menu-item>
                        <router-link
                          style="font-size: 10px"
                          to="/collectstores"
                        >
                          <HeartOutlined
                            style="color: red; margin-right: 3px"
                          />收藏的店铺
                        </router-link>
                      </a-menu-item>
                    </a-menu>
                  </template>
                </a-dropdown>
                <router-link to="/cart"
                  ><ShoppingCartOutlined
                    style="color: red; margin-right: 5px"
                  />
                  购物车
                </router-link>
              </a-space>
            </div>
          </a-col>
          <a-col
            :span="4"
            style="
              justify-content: flex-end;
              align-items: center;
              display: flex;
            "
          >
          <a-space :size="10">
          <div>{{ userStore.user.nickName }}</div>
            <div>
              <a-avatar :src="userStore.user.avatar" :size="50" />
            </div>
          </a-space>
          </a-col>
        </a-row>
      </a-layout-header>
    </a-affix>
    <a-layout-content :style="contentStyle">
      <a-card style="background-color: #fff; height: 120vh; margin: 10px">
        <a-row>
          <a-col :span="2">
            <a-space direction="vertical" :size="30">
              <router-link :to="{ name: 'About' }"
                ><AreaChartOutlined
                  style="color: #409eff; margin-right: 5px"
                />数据中心
              </router-link>
              <router-link :to="{ name: 'Store' }"
                ><BankOutlined
                  style="color: #e6a23c; margin-right: 5px"
                />我的店铺
              </router-link>
              <router-link :to="{ name: 'Order' }"
                ><ShoppingOutlined style="color: #67c23a; margin-right: 5px" />
                我的订单
              </router-link>
              <router-link :to="{ name: 'MyGoods' }"
                ><InboxOutlined style="color: #f50; margin-right: 5px" />
                我的宝贝
              </router-link>
              <router-link :to="{ name: 'Address' }"
                ><FormOutlined style="color: #606266; margin-right: 5px" />
                收获地址
              </router-link>
            </a-space>
          </a-col>

          <a-col
            :span="22"
            style="background-color: #f2f6fc; padding: 10px; height: 115vh"
          >
            <router-view></router-view>
          </a-col>
        </a-row>
      </a-card>
    </a-layout-content>

    <!-- 实名认证右侧弹框 -->
    <div>
      <a-drawer
        v-model:open="openDrawer"
        :body-style="{ paddingBottom: '80px' }"
        :footer-style="{ textAlign: 'right' }"
        title="实名认证"
        :width="720"
      >
        <a-form
          ref="PhoneFormRef"
          :rules="PhoneRules"
          :model="user"
          layout="vertical"
        >
          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item label="姓名" name="name">
                <a-input
                  placeholder="请输入真实姓名"
                  style="width: 100%"
                  v-model:value="user.name"
                  maxlength="10"
                  minlength="2"
                  size="large"
                >
                </a-input>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="身份证" name="idCard">
                <a-input
                  placeholder="请输入真实身份证号"
                  style="width: 100%"
                  v-model:value="user.idCard"
                  maxlength="18"
                  minlength="18"
                  size="large"
                >
                </a-input>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="16">
            <a-col v-if="isRegisterPwd" :span="12">
              <a-form-item label="昵称" name="nickName">
                <a-input
                  placeholder="请设置用户昵称"
                  style="width: 100%"
                  v-model:value="user.nickName"
                  maxlength="5"
                  minlength="5"
                  size="large"
                >
                </a-input>
              </a-form-item>
            </a-col>
            <a-col v-if="isRegisterPwd" :span="12">
              <a-form-item label="密码" name="password">
                <a-input
                  placeholder="请设置用户密码"
                  style="width: 100%"
                  v-model:value="user.password"
                  minlength="6"
                  size="large"
                >
                </a-input>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="16">
            <a-col v-if="isRegisterPhone" :span="12">
              <a-form-item label="手机号" name="phone">
                <a-input
                  placeholder="请输入手机号"
                  style="width: 100%"
                  v-model:value="user.phone"
                  minlength="11"
                  maxlength="11"
                  size="large"
                >
                </a-input>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="性别" name="sex">
                <a-radio-group
                  style="width: 100%"
                  size="large"
                  v-model:value="user.sex"
                >
                  <a-radio value="男">男</a-radio>
                  <a-radio value="女">女</a-radio>
                </a-radio-group>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item label="地址" name="address">
                <a-textarea
                  placeholder="请输入现住真实地址"
                  style="width: 100%"
                  v-model:value="user.address"
                  size="large"
                  :rows="4"
                >
                </a-textarea>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
        <template #extra>
          <a-space>
            <a-button @click="onClose">取消</a-button>
            <a-button type="primary" @click="doCertification">认证</a-button>
          </a-space>
        </template>
      </a-drawer>
    </div>

    <!-- 修改密码弹框 -->
    <div>
      <a-modal
        v-model:open="modalVisible"
        title="修改密码"
        centered
        @ok="updatePwd"
        okText="保存"
        cancelText="取消"
        @cancel="cancelUpdatePwd"
      >
        <a-space
          style="padding: 20px 20px 20px 100px"
          direction="vertical"
          :size="30"
        >
          <a-input-password
            size="large"
            v-model:value="password.oldPassword"
            placeholder="原密码"
          />
          <a-input-password
            size="large"
            v-model:value.lazy="password.newPassword"
            autofocus
            placeholder="新密码"
          />
        </a-space>
      </a-modal>
    </div>

    <!-- 修改个人信息弹框 -->
    <div>
      <a-modal
        v-model:open="Visible"
        title="个人信息"
        centered
        @ok="updatePersonal"
        okText="修改"
        cancelText="取消"
        @cancel="cancelUpdatePersonal"
      >
        <a-form
          ref="PhoneFormRef"
          :rules="PhoneRules"
          :model="personal"
          :label-col="labelCol"
          :wrapper-col="wrapperCol"
        >
          <a-form-item ref="nickName" label="昵称" name="nickName">
            <a-input v-model:value="personal.nickName" placeholder="昵称" />
          </a-form-item>
          <a-form-item ref="password" label="密码" name="password">
            <a-input-password
              v-model:value="personal.password"
              placeholder="密码"
            />
          </a-form-item>
          <a-form-item ref="phone" label="手机号" name="phone">
            <a-input
              v-model:value.lazy="personal.phone"
              autofocus
              placeholder="手机号"
            />
          </a-form-item>
          <a-form-item ref="code" label="验证码" name="code">
            <a-input-search
              v-model:value="personal.code"
              placeholder="请输入验证码"
              @search="onSearch"
              style="width: 100%"
              maxlength="6"
              minlength="6"
            >
              <template #enterButton>
                <a-button
                  @click="getCode"
                  :disabled="disabled"
                  style="
                    background-color: #409eff;
                    color: #fff;
                    font-size: 10px;
                  "
                  >{{ content }}</a-button
                >
              </template>
            </a-input-search>
          </a-form-item>
          <a-form-item ref="sex" label="性别" name="sex">
            <a-radio-group style="width: 100%" v-model:value="personal.sex">
              <a-radio value="男">男</a-radio>
              <a-radio value="女">女</a-radio>
            </a-radio-group>
          </a-form-item>
          <a-form-item ref="avatar" label="头像" name="avatar">
            <a-upload
              v-model:file-list="fileList"
              name="avatar"
              list-type="picture-card"
              class="avatar-uploader"
              :show-upload-list="false"
              :customRequest="customRequestPersonal"
              :before-upload="beforeUpload"
              @change="handleChange"
            >
              <img
                style="height: 100px; width: 100px; border-radius: 10%"
                v-if="personal.avatar"
                :src="personal.avatar"
                alt="avatar"
              />
              <div v-else>
                <loading-outlined v-if="loading"></loading-outlined>
                <plus-outlined v-else></plus-outlined>
                <div class="ant-upload-text">头像</div>
              </div>
            </a-upload>
          </a-form-item>
          <a-form-item ref="address" label="现存地址" name="address">
            <a-input
              v-model:value.lazy="personal.address"
              autofocus
              :disabled="true"
            />
          </a-form-item>
          <a-form-item ref="regions" label="所在地区" name="regions">
            <a-cascader
              v-model:value="personal.regions"
              :options="options"
              placeholder="请选择地区"
              expand-trigger="hover"
            />
          </a-form-item>
          <a-form-item ref="detail" label="详细地址" name="detail">
            <a-textarea
              placeholder="请输入现住真实地址"
              style="width: 100%"
              v-model:value="personal.detail"
              :rows="4"
            >
            </a-textarea>
          </a-form-item>
        </a-form>
      </a-modal>
    </div>
  </a-layout>
</template>
<script setup>
import {
  AreaChartOutlined,
  ShoppingCartOutlined,
  ShoppingOutlined,
  FormOutlined,
  DownOutlined,
  HomeOutlined,
  BankOutlined,
  UserOutlined,
  LockOutlined,
  StarOutlined,
  HeartOutlined,
  ContactsOutlined,
  InboxOutlined,
} from "@ant-design/icons-vue";
import { ref, onMounted } from "vue";
import {
  certification,
  updatePassword,
  updatePerson,
  echo,
} from "@/api/certification";
import { message } from "ant-design-vue";
import { upload } from "@/api/upload";
import { useUserStore } from "@/stores/user";
import { useAuthorizationStore } from "@/stores/authorization";
import router from "@/router";
import { sendMs } from "@/api/sendMs";
import { getAreaData } from "@/api/address";
import {logo} from "@/stores/logo.js";

const headerLogo = ref("");
headerLogo.value = logo;

const isConfrim = ref(false);
const confirm = ref("已认证");
const notConfirm = ref("未认证，请点击认证");
onMounted(() => {
  if (userStore.user.idCard) {
    isConfrim.value = true;
  }
  getAllAreaData();
});

const options = ref([]);
//获取省市区数据
function getAllAreaData() {
  getAreaData().then((res) => {
    if (res.code === 200) {
      options.value = res.data;
    }
  });
}
const userStore = useUserStore();
const authorizationStore = useAuthorizationStore();
const user = ref({
  id: null,
  name: "",
  nickName: "",
  idCard: "",
  password: "",
  phone: "",
  sex: "",
  address: "",
});
const PhoneFormRef = ref();
const PhoneRules = {
  phone: [
    {
      required: true,
      message: "请输入手机号",
      trigger: "change",
    },
    {
      min: 11,
      max: 11,
      message: "长度为11个字符",
      trigger: "blur",
    },
  ],
  code: [
    {
      required: true,
      message: "请输入验证码",
      trigger: "blur",
    },
  ],
  nickName: [
    {
      required: true,
      message: "请设置昵称",
      trigger: "blur",
    },
    {
      min: 5,
      max: 5,
      message: "长度为5个字符",
      trigger: "blur",
    },
  ],
  password: [
    {
      required: true,
      message: "请设置密码",
      trigger: "blur",
    },
  ],
  avatar: [
    {
      required: true,
      message: "请设置用户头像",
      trigger: "blur",
    },
  ],
  name: [
    {
      required: true,
      message: "请输入真实姓名",
      trigger: "blur",
    },
  ],
  idCard: [
    {
      required: true,
      message: "请输入身份证号",
      trigger: "blur",
    },
    {
      min: 18,
      max: 18,
      message: "长度为18个字符",
      trigger: "blur",
    },
  ],
  sex: [
    {
      required: true,
      message: "请选择性别",
      trigger: "blur",
    },
  ],
  detail: [
    {
      required: true,
      message: "请输入详细地址",
      trigger: "blur",
    },
  ],
  regions: [
    {
      required: true,
      message: "请选择地址",
      trigger: "blur",
    },
  ],
};
//头像上传部分
const fileList = ref([]);

const openDrawer = ref(false);
const isRegisterPwd = ref(false);
const isRegisterPhone = ref(false);
function certificationRight() {
  if (userStore.user.idCard) {
    message.success("您已认证通过，无需重复认证！");
  } else {
    openDrawer.value = true;
    if (!userStore.user.nickName) {
      isRegisterPwd.value = true;
    }
    if (!userStore.user.phone) {
      isRegisterPhone.value = true;
    }
  }
}

//身份证号校验
let IdCardReg =
  /^[1-9]\d{5}(19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
//用户认证方法，
function doCertification() {
  PhoneFormRef.value
    .validate()
    .then(() => {
      //手机号验证
      if (!IdCardReg.test(user.value.idCard)) {
        message.error("请输入正确的身份证号");
      } else {
        user.value.id = userStore.user.key;
        certification(user.value).then((res) => {
          if (res.code === 200) {
            message.success("恭喜认证成功！");
            userStore.removeUser();
            userStore.setUser(res.data);
            openDrawer.value = false;
            window.location.reload();
          }
        });
      }
    })
    .catch((error) => {
      console.log("error", error);
    });
}

//取消认证方法
function onClose() {
  user.value = {};
  openDrawer.value = false;
}

const beforeUpload = (file) => {
  const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
  if (!isJpgOrPng) {
    message.error("限定上传jpg/png格式!");
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error("文件大于2MB!");
  }
  return isJpgOrPng && isLt2M;
};

const modalVisible = ref(false);
function setModelVisible() {
  modalVisible.value = true;
}
const password = ref({
  id: null,
  oldPassword: "",
  newPassword: "",
});

//修改密码
function updatePwd() {
  if (password.value.oldPassword === "" || password.value.newPassword === "") {
    message.error("密码不能为空");
  } else {
    password.value.id = userStore.user.key;
    updatePassword(password.value).then((res) => {
      if (res.code === 200) {
        message.success("修改成功，请重新登录！");
        password.value = {};
        modalVisible.value = false;
        //强制重新登录
        userStore.removeUser();
        authorizationStore.removeAuthorization();
        router.push("/login");
      }
    });
  }
}

//取消修改密码
function cancelUpdatePwd() {
  password.value = {};
  modalVisible.value = false;
}

//修改个人信息弹框
//头像上传部分
function customRequestPersonal(file) {
  upload(file).then((res) => {
    if (res.code === 200) {
      personal.value.avatar = res.data;
    }
  });
}
const personal = ref({
  id: null,
  nickName: "",
  password: "",
  phone: "",
  code: "",
  sex: "",
  avatar: "",
  address: "",
  regions: [],
  detail: "",
});
const Visible = ref(false);
function setVisible() {
  Visible.value = true;
  //获取个人信息数据回显
  echo(userStore.user.key).then((res) => {
    if (res.code === 200) {
      personal.value = res.data;
    }
  });
}

//获取验证码前确认是否是真实手机号
const disabled = ref(false);
const content = ref("获取验证码");
function getCode() {
  //请求发送短信
  if (personal.value.phone !== "") {
    sendMs(personal.value.phone).then((res) => {
      if (res.code === 200) {
        message.success("发送成功!");
      }
    });
    var time = 180;
    //禁用获取验证码按钮
    disabled.value = true;
    // 开启定时器
    var timer = setInterval(function () {
      // 判断剩余秒数
      if (time == 0) {
        // 清除定时器和复原按钮
        clearInterval(timer);
        disabled.value = false;
        content.value = "获取验证码";
      } else {
        content.value = `${time}秒后重新获取`;
        time--;
      }
    }, 1000);
  } else {
    message.error("请输入手机号");
  }
}
//修改个人信息
function updatePersonal() {
  PhoneFormRef.value
    .validate()
    .then(() => {
      personal.value.address = "";
      personal.value.id = userStore.user.key;
      for (var i = 0; i < personal.value.regions.length; i++) {
        personal.value.address += personal.value.regions[i];
      }
      personal.value.address += personal.value.detail;
      updatePerson(personal.value).then((res) => {
        if (res.code === 200) {
          message.success("修改成功，请重新登录！");
          personal.value = {};
          Visible.value = false;
          //强制重新登录
          userStore.removeUser();
          authorizationStore.removeAuthorization();
          router.push("/login");
        }
      });
    })
    .catch((error) => {
      console.log("error", error);
    });
}

//取消修改个人信息
function cancelUpdatePersonal() {
  personal.value = {};
  Visible.value = false;
}

const labelCol = {
  style: {
    width: "150px",
  },
};
const wrapperCol = {
  span: 10,
};

const headerStyle = {
  color: "black",
  height: "85px",
  backgroundColor: "#fff",
};
const contentStyle = {
  minHeight: "100vh",
  color: "black",
  backgroundColor: "#F2F6FC",
};
</script>
<style scoped>
a:hover {
  color: red;
}
a:link {
  color: black;
}
.content_top {
  /* #f4f4f5 */
  background-color: #f4f4f5;
  height: 100vh;
  width: 80%;
}

.content_left {
  color: black;
  width: 140px;
  background-color: #fff;
  height: 100vh;
}

.content_right {
  margin-top: 10px;
  background-color: #fff;
  height: 95vh;
  width: 173vh;
}

:deep(.ant-card-body) {
  padding: 20px;
}
</style>